﻿using System;
using System.Linq;
using Coevery.ViewModel.EntityDataService;
using System.Data.Services.Client;
using System.Windows.Controls.Primitives;

namespace Coevery.ViewModel
{
    public class OpportunityViewModel : BaseViewModel
    {
        public Guid OpportunityId { get; set; }
        public Popup Popup { get; set; }
        public event EventHandler EnableButton;

        private DataServiceCollection<Opportunity> _opportunities;

        public DataServiceCollection<Opportunity> Opportunities
        {
            get { return _opportunities; }
            set
            {
                _opportunities = value;
                _opportunities.LoadCompleted += LoadOpportunityData;
                OnPropertyChanged("Opportunities");
            }
        }

        private DataServiceCollection<Note> _notes;

        public DataServiceCollection<Note> Notes
        {
            get { return _notes; }
            set
            {
                _notes = value;
                _notes.LoadCompleted += LoadCommentData;
                OnPropertyChanged("Notes");
            }
        }

        public void LoadData()
        {
            if (!Popup.IsOpen)
            {
                Popup.IsOpen = true;
                EnableButton.Invoke(false, null);
            }
            Opportunities = new DataServiceCollection<Opportunity>(Context);
            Notes = new DataServiceCollection<Note>(Context);
            var query = (from cust in Context.Opportunities.Expand("Customer").Expand("Owner").Expand("Department")
                         where cust.OpportunityId == OpportunityId && cust.IsDeleted == false
                         select cust);
            Opportunities.LoadAsync(query);
        }

        private void LoadOpportunityData(object sender, LoadCompletedEventArgs e)
        {
            if (Opportunities.Continuation != null)
            {
                Opportunities.LoadNextPartialSetAsync();
            }

            Notes.LoadAsync((from cust in Context.Notes.Expand("ModifiedBy") where cust.ObjectType == "Opportunity" && cust.ObjectId == OpportunityId && cust.IsDeleted == false orderby cust.CreatedOn descending select cust));
        }

        private void LoadCommentData(object sender, LoadCompletedEventArgs e)
        {
            if (Notes.Continuation != null)
            {
                Notes.LoadNextPartialSetAsync();
            }
            Popup.IsOpen = false;
            EnableButton.Invoke(true, null);
        }
    }
}
